package com.xja.service.impl;

import com.xja.common.JsonBean;
import com.xja.entity.MenuVo;
import com.xja.mapper.SysMenuMapper;
import com.xja.service.IndexService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author CHENCHEN
 * @company 北京学佳澳教育科技
 * @create 2024-01-16 15:44
 */
@Service
public class IndexServiceImpl implements IndexService {

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Override
    public JsonBean login(String username, String password, HttpSession session) {
        //TODO: 验证登录
        Integer roleId = 4;
        //当前角色有拥有的所有菜单
        List<MenuVo> allMenuList = sysMenuMapper.loginMenuByRoleId(roleId);
        List<MenuVo> firstMenu = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        for (MenuVo menu: allMenuList) {
            if(menu.getpId().equals(0)){
                //当前是一级菜单
                firstMenu.add(menu);
                /**
                 * 一级菜单的ID是下一级菜单的Pid
                 */
                List<Object> list = new ArrayList<>();
                for(MenuVo nextMenu: allMenuList){
                    if(menu.getId().equals(nextMenu.getpId())){
                        //找到了二级菜单
                        getNextMenu(nextMenu, allMenuList);
                        list.add(nextMenu);
                    }
                }
                map.put(menu.getDescription(), list);
            }
        }
        session.setAttribute("firstMenu", firstMenu);
        session.setAttribute("nextMenu", map);
        return null;
    }

    private void getNextMenu(MenuVo nowMenu, List<MenuVo> allMenu){
        List<MenuVo> childrenList = new ArrayList<>();
        for (MenuVo nextMenu: allMenu){
            if(nowMenu.getId().equals(nextMenu.getpId())){
                //找到了下一级
                getNextMenu(nextMenu, allMenu);
                childrenList.add(nextMenu);
            }
        }
        nowMenu.setChildren(childrenList);
    }
}
